package com.bsoft.wx.controller;

import com.bsoft.wx.config.shiro.JwtUtil;
import com.bsoft.wx.service.TbUserService;
import com.bsoft.wx.util.R;
import com.bsoft.wx.vo.LoginForm;
import com.bsoft.wx.vo.RegisterFrom;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author hdh
 * @ Data   :Created in 14:19 2023/2/12
 * @ Description 用户接口
 * @ Modified By: hdh
 * @ Version : 1.0
 */
@RestController
@RequestMapping("/user")
@Api("用户模块接口web")
@Slf4j
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${emos.jwt.cahe-expire}")
    private int cacheExpire;
    @Autowired
    private TbUserService tbUserService;
    @Autowired
    private JwtUtil jwtUtil;

    //注册流程
    @PostMapping("/register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterFrom registerFrom) {
        int userId = tbUserService.registerUser(registerFrom.getRegisterCode(), registerFrom.getCode(), registerFrom.getNickname(), registerFrom.getPhoto());
        log.info("用户id" + userId);
        String token = jwtUtil.createToken(userId);
        log.info("生成token" + token);
        Set<String> permsSet = tbUserService.searchUserPermissions(userId);
        log.info("用户权限" + permsSet);
        saveCacheToken(token, userId);
        return R.ok("用户注册成功").put("token", token).put("permission", permsSet);


    }

    //保存token
    private void saveCacheToken(String token, int userId) {
        redisTemplate.opsForValue().set(token, userId + "", cacheExpire, TimeUnit.DAYS);
    }

    // 登录
    @PostMapping("/login")
    @ApiOperation("登录系统")
    public R login(@Valid @RequestBody LoginForm loginForm) {
        Integer id = tbUserService.login(loginForm.getCode());
        String token = jwtUtil.createToken(id);
        log.info("token" + token);
        Set<String> permissions = tbUserService.searchUserPermissions(id);
        log.info("permisson 权限列表" + permissions);
        saveCacheToken(token, id);
        return R.ok("登录成功").put("token", token).put("permission", permissions);
    }

}
